package com.eshunda.eshunda_android_demo;

import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.ImageButton;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import com.alibaba.fastjson.JSONObject;
import com.eshunda.ldt.SdkManager;
import com.eshunda.ldt.bean.DetectResult;
import com.eshunda.ldt.bean.InitConfig;
import com.eshunda.ldt.biz.DetectCallback;
import com.google.android.material.button.MaterialButton;
import com.google.android.material.textfield.TextInputEditText;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;

/**
 * 实人认证 - 信息填写 + 刷脸认证
 * 参考页面: https://face.eshunda.cn/h5demo/real-person
 */
public class RealPersonActivity extends AppCompatActivity implements View.OnClickListener {

    private static final String TAG = "RealPersonActivity";
    private static final String CAMERA_ID = "1";
    private static final int THREAD_POOL_SIZE = 3;
    private static final int EXECUTOR_SHUTDOWN_TIMEOUT_SECONDS = 5;
    private static final int DEFAULT_LIVENESS_TYPE = 2; // 眨眼

    private ImageButton btnBack;
    private TextInputEditText etName;
    private TextInputEditText etIdNumber;
    private MaterialButton btnNext;

    private SdkManager sdkManager;
    private HTTPClient httpClient;
    private ExecutorService executorService;

    private String token;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_real_person);

        initSdk();
        initViews();
        initExecutor();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        shutdownExecutor();
    }

    private void initSdk() {
        SdkManager.Init();
        SdkManager.cameraID = CAMERA_ID;
        httpClient = new HTTPClient();
        sdkManager = new SdkManager(this);
    }

    private void initViews() {
        btnBack = findViewById(R.id.btn_back);
        etName = findViewById(R.id.et_name);
        etIdNumber = findViewById(R.id.et_id_number);
        btnNext = findViewById(R.id.btn_next);

        btnBack.setOnClickListener(this);
        btnNext.setOnClickListener(this);

        TextWatcher watcher = new TextWatcher() {
            @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) {}
            @Override public void onTextChanged(CharSequence s, int start, int before, int count) { validateForm(); }
            @Override public void afterTextChanged(Editable s) { validateForm(); }
        };
        etName.addTextChangedListener(watcher);
        etIdNumber.addTextChangedListener(watcher);

        validateForm();
    }

    private void initExecutor() {
        executorService = Executors.newFixedThreadPool(THREAD_POOL_SIZE, new ThreadFactory() {
            @Override
            public Thread newThread(@NonNull Runnable r) {
                return new Thread(r, "RealPerson-Worker");
            }
        });
    }

    private void shutdownExecutor() {
        if (executorService != null && !executorService.isShutdown()) {
            executorService.shutdown();
            try {
                if (!executorService.awaitTermination(EXECUTOR_SHUTDOWN_TIMEOUT_SECONDS, TimeUnit.SECONDS)) {
                    executorService.shutdownNow();
                }
            } catch (InterruptedException e) {
                Log.e(TAG, "Error shutting down executor", e);
                executorService.shutdownNow();
                Thread.currentThread().interrupt();
            }
        }
    }

    private void validateForm() {
        String name = getText(etName);
        String id = getText(etIdNumber);
        boolean valid = !TextUtils.isEmpty(name) && isValidIdNumber(id);
        btnNext.setEnabled(valid);
        btnNext.setAlpha(valid ? 1f : 0.5f);
    }

    private String getText(TextInputEditText editText) {
        return editText.getText() == null ? "" : editText.getText().toString().trim();
    }

    private boolean isValidIdNumber(String id) {
        if (TextUtils.isEmpty(id)) return false;
        // 简单规则: 18位(最后一位可为X/x)或15位数字
        return id.matches("^(\\d{15}|\\d{17}[0-9Xx])$");
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        if (id == R.id.btn_back) {
            finish();
            return;
        }
        if (id == R.id.btn_next) {
            startRealPersonFlow();
        }
    }

    private void startRealPersonFlow() {
        final String name = getText(etName);
        final String idNumber = getText(etIdNumber);

        executorService.execute(() -> {
            try {
                // 1) 初始化SDK配置
                InitConfig config = new InitConfig(DEFAULT_LIVENESS_TYPE);
                DetectResult initResult = sdkManager.authInit(config);
                if (initResult == null || initResult.getData() == null) {
                    Log.e(TAG, "SDK初始化失败");
                    return;
                }

                // 2) 获取token - 实人认证(real)
                String tokenResp = httpClient.authInitReal(initResult.getData(), name, idNumber);
                if (TextUtils.isEmpty(tokenResp)) {
                    Log.e(TAG, "获取token失败：响应为空");
                    return;
                }
                JSONObject tokenJson = JSONObject.parseObject(tokenResp);
                String code = tokenJson.getString("code");
                if (!"200".equals(code)) {
                    Log.e(TAG, "获取token失败：状态码为:" + code);
                    return;
                }
                token = tokenJson.getJSONObject("data").getString("token");
                if (TextUtils.isEmpty(token)) {
                    Log.e(TAG, "获取token失败：token为空");
                    return;
                }

                // 3) 启动刷脸
                sdkManager.startLivingDetect(token, new DetectCallback() {
                    @Override
                    public void onFinish(DetectResult result) {
                        handleVerifyResult(result);
                    }
                });
            } catch (Exception e) {
                Log.e(TAG, "实人认证流程错误", e);
            }
        });
    }

    private void handleVerifyResult(final DetectResult result) {
        if (result == null) {
            Log.e(TAG, "检测结果为空");
            return;
        }

        executorService.execute(() -> {
            try {
                String verifyResp = httpClient.authReal(result);
                Log.d(TAG, "实人认证结果：" + verifyResp);
                // TODO: 可根据返回结果做成败提示
            } catch (Exception e) {
                Log.e(TAG, "提交实人认证结果失败", e);
            }
        });
    }
}


